package com.tcs.hive.api.hql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class HqlMain {

	private static Logger logger = LoggerFactory.getLogger(HqlMain.class);

									//  org.apache.hadoop.hive.jdbc.HiveDriver
	private String driverName = "org.apache.hive.jdbc.HiveDriver";
	
	private String url = "jdbc:hive2://slave1:10000/default";

	private Connection con = null;

	public void init() {
		logger.info(" 启动hive 程序!");
		try {
			Class.forName(driverName);
			con = DriverManager.getConnection(url, "wangbo", "");
		} catch (ClassNotFoundException e) {
			logger.error("获取驱动失败! ", e);
		} catch (SQLException e) {
			logger.error("连接失败! ", e);
		}
	}

	public void close() {
		try {
			con.close();
		} catch (SQLException e) {
			logger.error("关闭失败! ", e);
		}
	}

	public static void main(String[] args) {
		HqlMain hqlMain = new HqlMain();
		hqlMain.init();
		hqlMain.work();
		hqlMain.close();
	}

	public void work() {
		try {
			Statement stmt = con.createStatement();
//			stmt.executeQuery("CREATE database hive_demo1");
			stmt.execute("use hive_demo1");
			//stmt.execute("create table hive_table1(id int , name varchar(20), age int)");
			ResultSet resultSet = stmt.executeQuery("select * from hive_table1");
			while (resultSet.next()) {
				logger.info(" id  : {} " , resultSet.getInt("id"));
				logger.info("name : {} " , resultSet.getString("name"));
				logger.info(" age  : {} " , resultSet.getInt("age"));
			}
		} catch (SQLException e) {
			logger.error("执行失败!! ", e);
		}
	}

}
